package com.ttxs.common.core.server;

import org.apache.catalina.*;
import org.apache.catalina.session.ManagerBase;
import org.apache.tomcat.util.ExceptionUtils;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;

import java.io.IOException;

/**
 * 关闭tomcat创建session功能
 */
public class TomcatFactory extends TomcatServletWebServerFactory {

    protected void postProcessContext(Context context) {
        context.setManager(new NoSessionManager());
    }

    class NoSessionManager extends ManagerBase implements Lifecycle {

        @Override
        protected synchronized void startInternal() throws LifecycleException {
            super.startInternal();
            try {
                load();
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                t.printStackTrace();
            }
            setState(LifecycleState.STARTING);
        }

        @Override
        protected synchronized void stopInternal() throws LifecycleException {
            setState(LifecycleState.STOPPING);
            try {
                unload();
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                t.printStackTrace();
            }
            super.stopInternal();
        }

        @Override
        public void load() throws ClassNotFoundException, IOException {
            System.err.println("HttpSession 已经关闭,若开启请配置：ttxs.tomcat.disableSession=false");
        }

        @Override
        public void unload() throws IOException {}
        @Override
        public Session createSession(String sessionId) {
            return null;
        }

        @Override
        public Session createEmptySession() {
            return null;
        }

        @Override
        public void add(Session session) {}
        @Override
        public Session findSession(String id) throws IOException {
            return null;
        }
        @Override
        public Session[] findSessions(){
            return null;
        }
        @Override
        public void processExpires() {}
    }
}

